package com.jiamao.goplay.ui.discover;

import android.app.Activity;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.viewpager.widget.ViewPager;

import com.gyf.immersionbar.ImmersionBar;
import com.gyf.immersionbar.OnKeyboardListener;
import com.jiamao.goplay.BR;
import com.jiamao.goplay.R;
import com.jiamao.goplay.adapter.NearbyAdapter;
import com.jiamao.goplay.app.AppViewModelFactory;
import com.jiamao.goplay.base.BaseMVVMFragment;
import com.jiamao.goplay.bean.res.ResMatch;
import com.jiamao.goplay.databinding.DiscoverCityGotoLayoutBinding;
import com.jiamao.goplay.databinding.DiscoverMatchLayoutBinding;
import com.jiamao.goplay.ui.discover.vm.CityGoToVM;
import com.jiamao.goplay.ui.discover.vm.MatchVM;
import com.jiamao.goplay.util.GsonUtil;
import com.jiamao.goplay.util.KeyInputUtils;
import com.jiamao.goplay.view.InputEditText;
import com.netease.nim.uikit.api.NimUIKit;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.youth.banner.util.LogUtils;

import me.goldze.mvvmhabit.base.AppManager;

public class MatchFragment extends BaseMVVMFragment<DiscoverMatchLayoutBinding, MatchVM> implements View.OnLayoutChangeListener {

    AlertDialog dialog;

    String name;
    @Override
    public int initVariableId() {
        return BR.viewModel;
    }


    @Override
    public MatchVM initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用LoginViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this, factory).get(MatchVM.class);
    }
    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.discover_match_layout;
    }

    @Override
    public void initViewObservable() {

        viewModel.uc.pSwitchEvent.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(@Nullable Integer aBoolean) {

                binding.pageIndicatorView.setCount(aBoolean);
                binding.pageIndicatorView.setSelection(0);
                binding.viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {/*empty*/}

                    @Override
                    public void onPageSelected(int position) {
                        binding.pageIndicatorView.setSelection(position);
                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {/*empty*/}
                });

            }
        });
        viewModel.uc.uiInitRefreshEvent.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(@Nullable Integer aBoolean) {

               // KeyInputUtils.hideInputMethodWindow(binding.editInput);

            }
        });

        super.initViewObservable();
        int screenHeight = getActivity().getWindowManager().getDefaultDisplay().getHeight();
        keyHeight = screenHeight/3;
        binding.panvie.addOnLayoutChangeListener(this);




//        binding.editInput.setOnKeyListener(new View.OnKeyListener() {
//
//            public boolean onKey(View v, int keyCode, KeyEvent event) {
//                if (keyCode == KeyEvent.KEYCODE_ENTER) {//回车键
//                    viewModel.sendTextMsg();
//                    return false;
//
//                }
//                return false;
//            }
//        });

    }

    @Override
    public void initData() {
        super.initData();
       // ImmersionBar.with(this). keyboardEnable(true).statusBarDarkFont(true).init();
      //  stateHidden|adjustResize
        ImmersionBar.with(this). keyboardEnable(true).statusBarDarkFont(true)
                    .keyboardMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING)
                .setOnKeyboardListener(new OnKeyboardListener() {    //软键盘监听回调，keyboardEnable为true才会回调此方法
                    @Override
                    public void onKeyboardChange(boolean isPopup, int keyboardHeight) {
                        LogUtils.e("isPopup "+isPopup);  //isPopup为true，软键盘弹出，为false，软键盘关闭
                    }
                }).init();
        String datas =  getArguments().getString("data");
        ResMatch data= (ResMatch) GsonUtil.toObject(datas,ResMatch.class);
        binding.editInput.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               // showAppDialog();
                NimUIKit.startP2PSession(getActivity(),viewModel.item.getBaseInfo().getId());
                    getActivity().finish();
            }
        });
        viewModel.update(data);
    }

    private  int  keyHeight ;
    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
        Log.i("iven","left:"+left+"\nright:"+right+"\ntop:"+top+"\nbottom:"+bottom);
        Log.i("iven","oldleft:"+oldLeft+"\nOldright:"+oldRight+"\ntop:"+oldTop+"\nbottom:"+oldBottom);

        //现在认为只要控件将Activity向上推的高度超过了1/3屏幕高，就认为软键盘弹起
        if(oldBottom != 0 && bottom != 0 &&(oldBottom - bottom > keyHeight)){
         //   binding.btnGoto.setVisibility(View.GONE);
           // Toast.makeText(getActivity(), "监听到软键盘弹起...", Toast.LENGTH_SHORT).show();

        }else if(oldBottom != 0 && bottom != 0 &&(bottom - oldBottom > keyHeight)){
          //  binding.btnGoto.setVisibility(View.VISIBLE);

            if (dialog!=null){
           //     dialog.dismiss();
            }
          //  Toast.makeText(getActivity(), "监听到软件盘关闭...", Toast.LENGTH_SHORT).show();

        }

    }


      private void showAppDialog(){

        View view = View.inflate(getActivity(), R.layout.app_dialog_input, null);
          InputEditText textView = view.findViewById(R.id.edit_input);
          textView.requestFocus();

        final TextView btnUpgrade = view.findViewById(R.id.btn_send);

         dialog = new AlertDialog.Builder(getActivity(),R.style.inputDialog)
                .setView(view)
                .create();
          Window window = dialog.getWindow();
          //设置弹出位置
          window.setGravity(Gravity.BOTTOM);
          WindowManager.LayoutParams layoutParams = window.getAttributes();
          window.setSoftInputMode(layoutParams.SOFT_INPUT_ADJUST_NOTHING);
          window.getDecorView().setPadding(0, 0, 0, 0);
          layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
          window.setAttributes(layoutParams);
          btnUpgrade.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewModel.hi.set(textView.getText().toString());
                viewModel.sendTextMsg();
                dialog.dismiss();
                KeyInputUtils.hideSoftInputView(getActivity());
            }
        });
          textView.setBackListener(new InputEditText.BackListener() {
              @Override
              public void back(TextView textView) {
                  dialog.dismiss();
                  KeyInputUtils.hideSoftInputView(getActivity());
              }
          });
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                dialog.dismiss();
                KeyInputUtils.hideSoftInputView(getActivity());
                return true;
            }
        });
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                //   client.remove();
                KeyInputUtils.hideSoftInputView(getActivity());
            }
        });
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                // client.remove();
                KeyInputUtils.hideSoftInputView(getActivity());
            }
        });
        dialog.show();

        KeyInputUtils.ShowKeyboard(textView);


    }

    @Override
    public void onResume() {
        super.onResume();
    }
}
